package com.admin.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.admin.common.enums.EnumIstatus;
import com.admin.common.enums.MemberLevelEnum;
import com.admin.common.util.DateUtils;
import com.admin.domain.Region;
import com.admin.domain.RoleDO;
import com.admin.req.system.UpdatePasswordReq;
import com.admin.req.user.AdminReq;
import com.admin.req.user.MemberReq;
import com.admin.service.RegionsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.admin.common.annotation.Log;
import com.admin.common.enums.EnumResult;
import com.admin.common.shiro.ShiroUtils;
import com.admin.common.util.YsCollectionUtil;
import com.admin.common.util.YsStringUtil;
import com.admin.controller.base.BaseController;
import com.admin.domain.AdminDO;
import com.admin.service.AdminService;
import com.admin.service.RoleService;
import com.admin.vo.PageVO;
import com.admin.vo.ResultVO;
import com.admin.vo.SimpleResultVO;
import com.admin.vo.system.AddAdminVO;
import com.admin.vo.system.AdminInfoVO;
import com.admin.vo.system.AdminLoginVO;
import com.admin.vo.system.IstatusSelectedVO;
import com.admin.vo.system.ListAdminVO;
import com.admin.vo.system.UpdateAdminVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 系统管理员接口
 * 
 * @author ZY
 * @date 2018/09/30
 */
@Api(description = "系统管理员接口")
@RestController
@RequestMapping(value = "/admin")
public class AdminController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(AdminController.class);
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RegionsService regionsService;

    @ApiOperation(value = "个人中心-登录")
    @PostMapping(value = "/login")
    @ApiImplicitParams(value = {
        @ApiImplicitParam(name = "username", value = "登录名", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "uuid", value = "uuid", required = true, dataType = "String", paramType = "query")})
    public ResultVO<AdminLoginVO> login(String username, String password, String code, String uuid) {
        logger.info("登录参数，username=" + username);
        return adminService.login(username, password, code, uuid);
    }

    @ApiOperation(value = "个人中心-退出")
    @GetMapping(value = "/logout")
    public SimpleResultVO logout() {
        ShiroUtils.logout();
        return SimpleResultVO.ok();
    }

    @ApiOperation(value = "个人中心-查询信息")
    @GetMapping(value = "/info")
    public ResultVO<AdminInfoVO> getAdminInfo() {
        return ResultVO.ok(adminService.getAdminInfoVO(getUserId()));
    }


    @Log(value = "updatePassword", title = "个人中心-修改密码")
    @ApiOperation(value = "个人中心-修改密码")
    @PostMapping(value = "/updatePassword")
    public SimpleResultVO updatePassword(@RequestBody UpdatePasswordReq passwordReq) {
        return adminService.updatePassWord(getUsername(), passwordReq.getOldPassword(), passwordReq.getNewPassword(), passwordReq.getConfirmPassword());
    }

    @ApiOperation(value = "重置密码")
    @GetMapping(value = "/resetPassWord")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "query")
    public ResultVO<Boolean> resetPassWord(Integer userId) {
        return ResultVO.ok(adminService.resetPassWord(userId));
    }


    @ApiOperation(value = "审核用户列表")
    @RequiresPermissions("admin:list")
    @GetMapping(value = "/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "realname", value = "姓名/手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "用户状态", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "开始时间", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "memberLevel", value = "用户级别", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "responsibleAreaId", value = "负责地区", dataType = "String", paramType = "query"),
    })
    public ResultVO<PageVO<ListAdminVO>> listAdmins(Integer pageIndex, Integer pageSize, String realname,
                                                    Integer status, Integer createTime, Integer endTime,
                                                    String memberLevel, String responsibleAreaId) {
        Map<String, Object> params = YsCollectionUtil.createHashMap();
        params.put("realname", realname);
        params.put("istatus", status);
        params.put("role", 0);
        params.put("memberLevel", memberLevel);
        if (!StringUtils.isEmpty(responsibleAreaId)) {
            List<Integer> resultList = new ArrayList<>();
            String[] responsibleArray = responsibleAreaId.split(",");
            if (responsibleArray != null) {
                for (String str : responsibleArray) {
                     String[] strArray = str.split("-");
                     String last = strArray[strArray.length - 1];
                     resultList.add(Integer.parseInt(last));
                }
                params.put("responsibleAreaIds", resultList);
            }
        }
        params.put("orderBy", "user_id");
        if (null != createTime && createTime != 0) {
            params.put("startTime", DateUtils.dateFormatStr(createTime));
        }
        if (null != endTime && endTime != 0) {
            params.put("endTime", DateUtils.dateFormatStr(endTime));
        }
        //匹配和自己有相同负责区域的用户
        if (!ShiroUtils.getMemberLevel().equals(MemberLevelEnum.PROVINCE.getKey())) {
            String businessStrIds = ShiroUtils.getUser().getBusinessAreaIds();
            StringBuffer stringBuffer = new StringBuffer();
            if (StringUtils.isNotEmpty(businessStrIds)) {
                String allBusinessIds = regionsService.findChildren(businessStrIds);
                String businessIds = allBusinessIds.replace(",","|");
                String newBusinessIds = businessIds.substring(0, businessIds.length() -1 );
                stringBuffer.append("',(").append(newBusinessIds).append("),'");
                params.put("businessAreaIds", stringBuffer.toString());
            }
        }
        logger.info("listAdmins params:{}", params);
        return adminService.getPageList(pageIndex, pageSize, params);
    }



    @ApiOperation(value = "到新增用户页")
//    @RequiresPermissions("admin:save")
    @GetMapping(value = "/toAdd")
    public ResultVO<AddAdminVO> toAddAdmin(Integer businessAreaId) {
        ResultVO<AddAdminVO> result = new ResultVO<>();
        AddAdminVO addAdminVO = new AddAdminVO();
        addAdminVO.setIstatusVOs(getIstatusSelectedVOs(EnumIstatus.OK.getKey()));
        addAdminVO.setRoleVOs(null);
        result.setData(addAdminVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }





    @ApiOperation(value = "审核用户列表 -  新增审核用户")
    @RequiresPermissions("admin:save")
    @PostMapping(value = "/saveAdmin")
    public SimpleResultVO saveAdmin(@RequestBody AdminReq req) {
        AdminDO adminDO = new AdminDO();
        BeanUtils.copyProperties(req, adminDO);
        return adminService.saveAdminDO(adminDO, req.getRoleIds());
    }


    @ApiOperation(value = "申报用户列表 -  新增申报用户")
//    @RequiresPermissions("admin:save")
    @PostMapping(value = "/saveMember")
    public SimpleResultVO saveMember(@RequestBody MemberReq req) {
        return adminService.saveMember(req);
    }

    @ApiOperation(value = "到修改用户页")
//    @RequiresPermissions("admin:list")
    @GetMapping(value = "/toUpdate")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "query")
    public ResultVO<UpdateAdminVO> toUpdateAdmin(Integer userId) {
        ResultVO<UpdateAdminVO> result = new ResultVO<>();
        UpdateAdminVO updateAdminVO = new UpdateAdminVO();
        AdminDO adminDO = adminService.selectByPrimaryKey(userId);
        BeanUtils.copyProperties(adminDO, updateAdminVO);
        updateAdminVO.setIstatusVOs(getIstatusSelectedVOs(adminDO.getIstatus()));
        updateAdminVO.setRoleVOs(roleService.getSelectRoles(userId).getData());
        result.setData(updateAdminVO);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }

    @ApiOperation(value = "审核用户列表 - 修改审核用户")
//    @RequiresPermissions("admin:update")
    @PostMapping(value = "/updateAdmin")
    public SimpleResultVO updateAdmin(@RequestBody AdminReq req) {
        AdminDO adminDO = new AdminDO();
        BeanUtils.copyProperties(req, adminDO);
        return adminService.updateAdminDO(adminDO, req.getRoleIds());
    }

    @ApiOperation(value = "申报用户列表 - 修改申报用户")
//    @RequiresPermissions("admin:update")
    @PostMapping(value = "/updateMember")
    public SimpleResultVO updateMember(@RequestBody MemberReq req) {
        return adminService.updateMember(req);
    }


    @ApiOperation(value = "删除用户")
    @RequiresPermissions("admin:delete")
    @GetMapping(value = "/delete")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int", paramType = "query")
    public SimpleResultVO deleteAdmin(Integer userId) {
        return adminService.deleteByPrimaryKey(userId);
    }

    @ApiOperation(value = "批量删除用户")
    @RequiresPermissions("admin:batchDelete")
    @PostMapping(value = "/batchDelete")
    @ApiImplicitParam(name = "userIds", value = "一组用户id，英文逗号分隔", required = true, dataType = "String",
        paramType = "query")
    public SimpleResultVO deleteAdmins(String userIds) {
        return adminService.deleteByPrimaryKeys(YsStringUtil.splitToInteger(userIds, ","));
    }

    @ApiOperation(value = "检查是否有效登录")
    @GetMapping(value = "/checkValidLogin")
    public SimpleResultVO checkValidLogin() {
        return SimpleResultVO.ok();
    }

    /**
     * 筛选账号状态
     * 
     * @param istatusSelected
     * @return
     */
    private List<IstatusSelectedVO> getIstatusSelectedVOs(Integer istatusSelected) {
        List<IstatusSelectedVO> istatusVOs = new ArrayList<IstatusSelectedVO>();
        for (EnumIstatus e : EnumIstatus.values()) {
            IstatusSelectedVO istatusVO = new IstatusSelectedVO();
            istatusVO.setIstatus(e.getKey());
            istatusVO.setIstatusName(e.getText());
            if (e.getKey().equals(istatusSelected)) {
                istatusVO.setIsSelected(true);
            } else {
                istatusVO.setIsSelected(false);
            }
            istatusVOs.add(istatusVO);
        }
        return istatusVOs;
    }
}
